//
//  OrderDetailViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 2016/10/18.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "MallViewController.h"
#import "CLUIBaseViewController.h"
#import "BLEHelpViewController.h"

@interface OrderDetailViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageViewGoods;
@property (weak, nonatomic) IBOutlet UILabel *labGoodsName;
@property (weak, nonatomic) IBOutlet UILabel *labGoodsColorNumber;
@property (weak, nonatomic) IBOutlet UILabel *labGoodsPrice;
@property (weak, nonatomic) IBOutlet UIImageView *imageStater;
@property (weak, nonatomic) IBOutlet UILabel *labStart;
@property (weak, nonatomic) IBOutlet UILabel *labAddress;//地址
@property (weak, nonatomic) IBOutlet UILabel *labUserInfo;//收货人信息
@property (weak, nonatomic) IBOutlet UILabel *labTransport;//运输方式
@property (weak, nonatomic) IBOutlet UILabel *labInvoice;//发票
@property (weak, nonatomic) IBOutlet UILabel *lableaveComments;//留言
@property (weak, nonatomic) IBOutlet UILabel *labTotalPrice;//商品总价
@property (weak, nonatomic) IBOutlet UILabel *labFreight;//运费
@property (weak, nonatomic) IBOutlet UILabel *labDiscount;//积分抵扣
@property (weak, nonatomic) IBOutlet UILabel *labActualPayment;//实际支付
@property (weak, nonatomic) IBOutlet UILabel *labReward;//积分奖励
@property (weak, nonatomic) IBOutlet UILabel *labNumbering;//订单编号
@property (weak, nonatomic) IBOutlet UILabel *labCreateTime;//创建时间
@property (weak, nonatomic) IBOutlet UILabel *labPaymentTime;//支付时间
@property (weak, nonatomic) IBOutlet UILabel *labelPaymentTitle;//付款时间
@property (weak, nonatomic) IBOutlet UILabel *labShipmentNumber;//发货单号
@property (weak, nonatomic) IBOutlet UILabel *labDeliveryTime;//发货时间
@property (weak, nonatomic) IBOutlet UILabel *labReceiptTime;//收货时间
@property (weak, nonatomic) IBOutlet UIButton *btnPayAndReceipt;
@property (weak, nonatomic) IBOutlet UILabel *labShiBie;//纳税人识别号
@property (strong, nonatomic) UIWindow *windowMask;
@property (strong, nonatomic) NSString *strURL;
@end

@implementation OrderDetailViewController
-(void)viewWillAppear:(BOOL)animated
{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单详情";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    [self requestOrderDetail];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadOrderDetailVC) name:@"reloadOrderDetailVC" object:nil];
    if (_orderType == OrderDetailTypePending) {
        self.labPaymentTime.hidden = YES;
        self.labelPaymentTitle.hidden = YES;
        self.imageStater.image = [UIImage imageNamed:@"icon_uncomplete"];
    }else if (_orderType == OrderDetailTypeCancel) {
        self.imageStater.image = [UIImage imageNamed:@"icon_error"];
    }else{
        self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
    }
}
- (void)dealloc{
    NSLog(@"reloadOrderDetailVC通知被移除");
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"reloadOrderDetailVC" object:nil];
}

- (void)reloadOrderDetailVC{
    self.tableView.scrollEnabled =YES;
    [self.btnView removeFromSuperview];
    [self.MoneyPayVC.view removeFromSuperview];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.strOrderid forKey:@"orderid"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserToken] forKey:@"token"];
    [[BaseDataRequest alloc] getOrderDetail:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableView.footer endRefreshing];
        if ([status isEqualToString:@"0"]) {
            [self.tableView reloadData];
            NSMutableDictionary *dicResult = [NSMutableDictionary dictionary];
            dicResult = [responseObject objectForKey:@"result"];
            [self.imageViewGoods sd_setImageWithURL:[NSURL URLWithString:[dicResult objectForKey:@"thumb_image"]] placeholderImage:[UIImage imageNamed:@"iocn_default"]];
            self.labGoodsName.text = [dicResult objectForKey:@"goodstitle"];
            self.labGoodsColorNumber.text = [dicResult objectForKey:@"standard_name"];
            if ([[dicResult objectForKey:@"order_type"] isEqualToString:@"2"]) {
                self.labGoodsPrice.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"one_price"]];
                self.labTotalPrice.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"total_price"]];
                self.labActualPayment.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"payamount"]];
            }else{
                self.labGoodsPrice.text = [NSString stringWithFormat:@"%@ 积分",[dicResult objectForKey:@"one_price"]];
                self.labTotalPrice.text = [NSString stringWithFormat:@"%@ 积分",[dicResult objectForKey:@"total_price"]];
                self.labActualPayment.text = [NSString stringWithFormat:@"%@ 积分",[dicResult objectForKey:@"payamount"]];
            }
            self.labAddress.text = [dicResult objectForKey:@"address"];
            self.labUserInfo.text =[NSString stringWithFormat:@"%@  %@", [dicResult objectForKey:@"consignee"], [dicResult objectForKey:@"consigneemobile"]];
            self.labTransport.text = [dicResult objectForKey:@"express_name"];
            self.labInvoice.text = [dicResult objectForKey:@"invoicetitle"];
            self.lableaveComments.text = [dicResult objectForKey:@"message"];
            self.labFreight.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"expensive"]];
            self.labDiscount.text = [dicResult objectForKey:@"exchange_amout"];
            self.labReward.text = [dicResult objectForKey:@"pointsuse"];
            self.labNumbering.text = [dicResult objectForKey:@"ordersn"];
            self.labCreateTime.text = [dicResult objectForKey:@"add_time"];
            self.labPaymentTime.text = [dicResult objectForKey:@"paytime"];
            self.labShipmentNumber.text = [dicResult objectForKey:@"logisticno"];
            if (![[dicResult objectForKey:@"logisticno"] isEqualToString:@""]) {
                NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[dicResult objectForKey:@"logisticno"]];
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                attch.image = [UIImage imageNamed:@"logistics"];
                attch.bounds = CGRectMake(0, -6, 58, 22);
                NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
                [attri appendAttributedString:string];
                self.labShipmentNumber.attributedText = attri;
                self.labShipmentNumber.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)];
                [self.labShipmentNumber addGestureRecognizer:tapGesture];
                //UIEdgeInsets insets = {0, 0, 0, 0};
                //self.labShipmentNumber.frame = UIEdgeInsetsInsetRect(self.labShipmentNumber.frame,insets);
                self.strURL = [dicResult objectForKey:@"logisticsurl"];
            }
            self.labDeliveryTime.text = [dicResult objectForKey:@"fhtime"];
            self.labReceiptTime.text = [dicResult objectForKey:@"receivetime"];
            NSString *status =  [dicResult objectForKey:@"status"] ;
            self.orderType = [status intValue];
            if ([status isEqualToString:@"0"]) {
                self.labStart.text = @"等待支付";
                self.imageStater.image = [UIImage imageNamed:@"icon_uncomplete"];
            }else if ([status isEqualToString:@"1"]){
                self.labStart.text = @"支付完成";
                self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
            }else if ([status isEqualToString:@"2"]){
                self.labStart.text = @"已发货";
                self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
                [self.btnPayAndReceipt setTitle:@"确认收货" forState:UIControlStateNormal];
            }else if ([status isEqualToString:@"3"]){
                self.labStart.text = @"订单完成";
                self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
            }else if ([status isEqualToString:@"4"]){
                self.labStart.text = @"订单取消";
                self.imageStater.image = [UIImage imageNamed:@"icon_error"];
                self.labelPaymentTitle.text = @"取消时间";
                self.labPaymentTime.text =[dicResult objectForKey:@"canceltime"];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];

}
#pragma mark - 数据请求
- (void)requestOrderDetail{
    [SVProgressHUD showWithStatus:@"获取订单详情.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.strOrderid forKey:@"orderid"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserToken] forKey:@"token"];
    [[BaseDataRequest alloc] getOrderDetail:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableView.footer endRefreshing];
        if ([status isEqualToString:@"0"]) {
            [self.tableView reloadData];
            NSMutableDictionary *dicResult = [NSMutableDictionary dictionary];
            dicResult = [responseObject objectForKey:@"result"];
            [self.imageViewGoods sd_setImageWithURL:[NSURL URLWithString:[dicResult objectForKey:@"thumb_image"]] placeholderImage:[UIImage imageNamed:@"iocn_default"]];
            self.labGoodsName.text = [dicResult objectForKey:@"goodstitle"];
            self.labGoodsColorNumber.text = [dicResult objectForKey:@"standard_name"];
            if ([[dicResult objectForKey:@"order_type"] isEqualToString:@"2"]) {
                self.labGoodsPrice.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"one_price"]];
                self.labTotalPrice.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"total_price"]];
                self.labActualPayment.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"payamount"]];
            }else{
                self.labGoodsPrice.text = [NSString stringWithFormat:@"%@ 积分",[dicResult objectForKey:@"one_price"]];
                self.labTotalPrice.text = [NSString stringWithFormat:@"%@ 积分",[dicResult objectForKey:@"total_price"]];
                self.labActualPayment.text = [NSString stringWithFormat:@"%@ 积分",[dicResult objectForKey:@"payamount"]];
            }
            self.labShiBie.text = [dicResult objectForKey:@"invoicenumber"];
            self.labAddress.text = [dicResult objectForKey:@"address"];
            self.labUserInfo.text =[NSString stringWithFormat:@"%@  %@", [dicResult objectForKey:@"consignee"], [dicResult objectForKey:@"consigneemobile"]];
            self.labTransport.text = [dicResult objectForKey:@"express_name"];
            self.labInvoice.text = [dicResult objectForKey:@"invoicetitle"];
            self.lableaveComments.text = [dicResult objectForKey:@"message"];
            self.labFreight.text = [NSString stringWithFormat:@"￥%@",[dicResult objectForKey:@"expensive"]];
            self.labDiscount.text = [dicResult objectForKey:@"exchange_amout"];
            self.labReward.text = [dicResult objectForKey:@"pointsuse"];
            self.labNumbering.text = [dicResult objectForKey:@"ordersn"];
            self.labCreateTime.text = [dicResult objectForKey:@"add_time"];
            self.labPaymentTime.text = [dicResult objectForKey:@"paytime"];
            self.labShipmentNumber.text = [dicResult objectForKey:@"logisticno"];
            if (![[dicResult objectForKey:@"logisticno"] isEqualToString:@""]) {
                NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[dicResult objectForKey:@"logisticno"]];
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                attch.image = [UIImage imageNamed:@"logistics"];
                attch.bounds = CGRectMake(0, -6, 58, 22);
                NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
                [attri appendAttributedString:string];
                self.labShipmentNumber.attributedText = attri;
                self.labShipmentNumber.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)];
                [self.labShipmentNumber addGestureRecognizer:tapGesture];
                //UIEdgeInsets insets = {0, 0, 0, 0};
                //self.labShipmentNumber.frame = UIEdgeInsetsInsetRect(self.labShipmentNumber.frame,insets);
                self.strURL = [dicResult objectForKey:@"logisticsurl"];
            }
            self.labDeliveryTime.text = [dicResult objectForKey:@"fhtime"];
            self.labReceiptTime.text = [dicResult objectForKey:@"receivetime"];
            NSString *status =  [dicResult objectForKey:@"status"] ;
            self.orderType = [status intValue];
            if ([status isEqualToString:@"0"]) {
                self.labStart.text = @"等待支付";
                self.imageStater.image = [UIImage imageNamed:@"icon_uncomplete"];
            }else if ([status isEqualToString:@"1"]){
                self.labStart.text = @"支付完成";
                self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
            }else if ([status isEqualToString:@"2"]){
                self.labStart.text = @"已发货";
                self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
                [self.btnPayAndReceipt setTitle:@"确认收货" forState:UIControlStateNormal];
            }else if ([status isEqualToString:@"3"]){
                self.labStart.text = @"订单完成";
                self.imageStater.image = [UIImage imageNamed:@"icon_completeicon"];
            }else if ([status isEqualToString:@"4"]){
                self.labStart.text = @"订单取消";
                self.imageStater.image = [UIImage imageNamed:@"icon_error"];
                self.labelPaymentTitle.text = @"取消时间";
                self.labPaymentTime.text =[dicResult objectForKey:@"canceltime"];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}


- (void)cancelOrder{
    [SVProgressHUD showWithStatus:@"取消订单.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.strOrderid forKey:@"orderid"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserToken] forKey:@"token"];
    [[BaseDataRequest alloc] cancelOrder:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableView.footer endRefreshing];
        if ([status isEqualToString:@"0"]) {
            TIPSFORVIEW(@"订单取消成功");
            if ([self.flag isEqualToString:@"1"]) {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

- (void)sureReceipt{
    [SVProgressHUD showWithStatus:@"确认收货.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] sureReceipt:self.strOrderid withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableView.footer endRefreshing];
        if ([status isEqualToString:@"0"]) {
            TIPSFORVIEW(@"收货成功");
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        UIWebView*callWebview =[[UIWebView alloc] init];
        NSURL *telURL =[NSURL URLWithString:@"tel:4009696966"];
        [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
        [self.view addSubview:callWebview];
        // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://4009696966"]];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 342;
    }else if (indexPath.row == 1){
        if (_orderType == OrderDetailTypePending ) {
            return 197;
        }else if (_orderType == OrderDetailTypePaid ) {
            return 223;
        }else if (_orderType == OrderDetailTypeShip ) {
            return 276;
        }else if(_orderType == OrderDetailTypeComplete){
            return 302;
        }else{//OrderDetailTypeCancel
            return 224;
        }
    }else if (indexPath.row == 2){
        if (_orderType == OrderDetailTypePending ) {
            return 120;
        }if (_orderType == OrderDetailTypeShip ) {
            return 63;
        }else{
            return 0;
        }
    }else{
        if (_orderType == OrderDetailTypePending || _orderType == OrderDetailTypeShip) {
            return 0;
        }else{
            
            return 110;//94
        }
    }
}

- (void)labelTap{
    BLEHelpViewController *help = [[BLEHelpViewController alloc] init];
    help.strURL = self.strURL;
    [self.navigationController pushViewController:help animated:YES];
}

#pragma mark - IBAction
- (IBAction)payAction:(id)sender {
    if (_orderType == OrderDetailTypeShip) {
        [self sureReceipt];
    }else if (_orderType == OrderDetailTypePending){
        //添加蒙层 弹出付款页面
        self.tableView.scrollEnabled =NO; //设置tableview 不能滚动
        self.btnView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.contentSize.height)];
        self.btnView.backgroundColor = [UIColor grayColor];
        [self.btnView addTarget:self action:@selector(btnViewClicked) forControlEvents:UIControlEventTouchUpInside];
        self.btnView.alpha = 0.6;
        [self.view addSubview:self.btnView];
        _MoneyPayVC = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"MoneyPay"];
        [self addChildViewController:_MoneyPayVC];
        _MoneyPayVC.view.frame = CGRectMake(0, self.tableView.contentSize.height-(self.tableView.contentSize.height-self.tableView.contentOffset.y-self.view.frame.size.height)-300, self.tableView.frame.size.width,300);
        _MoneyPayVC.view.alpha = 1.0;
        [self.view addSubview:_MoneyPayVC.view];
        _MoneyPayVC.orderId =  self.strOrderid;
        _MoneyPayVC.moneyLabel.text = self.labTotalPrice.text;
        NSMutableDictionary  *dic = [NSMutableDictionary new];
       [dic setObject:self.strOrderid forKey:@"orderid"];
        [dic setObject:@"1" forKey:@"ordertype"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"OrderPay" object:nil userInfo:dic];
    }
}

- (void)btnViewClicked
{
    self.tableView.scrollEnabled =YES; //设置tableview 能滚动
    [_MoneyPayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
}
- (IBAction)cancelAction:(id)sender {
    [self cancelOrder];
}

- (void)handleSingleTapFrom:(UITapGestureRecognizer *)recognizer {
    CGPoint point = [recognizer locationInView:self.view];
    NSLog(@"%f  %fY  %f",point.y,  self.tableView.contentOffset.y, (SCREEN_HEIGHT - 364) + self.tableView.contentOffset.y);
    if (point.y < (SCREEN_HEIGHT - 364) + self.tableView.contentOffset.y) {
        _windowMask.hidden = YES;
    }
}
-(void)backTo
{
    [super backTo];
    if ([self.flag isEqualToString:@"1"]) {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }
}
@end
